package com.happycat.filters;

import com.alibaba.fastjson.JSON;
import com.happycat.SysContants;
import com.happycat.model.LoginParam;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 构建用户名密码登录方式
 */
public class JsonAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException {
		if (!request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
		}
		if(request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)
                || request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)) {
			
			LoginParam loginParam = null;
			try {
                loginParam = JSON.parseObject(request.getInputStream(),Charset.forName(SysContants.UTF_8), LoginParam.class);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(loginParam == null) {
				throw new AuthenticationServiceException("请求数据格式不正确");
			}
			String username = loginParam.getAccount();
			String password = loginParam.getPassword();

			if (username == null) {
				username = "";
			}

			if (password == null) {
				password = "";
			}

			username = username.trim();

			UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);

			// Allow subclasses to set the "details" property
			setDetails(request, authRequest);
			this.setAuthenticationManager(super.getAuthenticationManager());
			return this.getAuthenticationManager().authenticate(authRequest);
		}else {
			return super.attemptAuthentication(request, response);
		}
			
	}
	
}
